package com.action.gulimall.product.service.impl;

import com.action.common.constant.ProductConstant;
import com.action.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.action.gulimall.product.entity.AttrGroupEntity;
import com.action.gulimall.product.entity.CategoryEntity;
import com.action.gulimall.product.vo.Attr;
import com.action.gulimall.product.vo.AttrRespVo;
import com.action.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.action.gulimall.product.dao.AttrDao;
import com.action.gulimall.product.entity.AttrEntity;
import com.action.gulimall.product.service.AttrService;
import com.action.common.utils.PageUtils;
import com.action.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    CategoryServiceImpl categoryService;
    @Autowired
    AttrGroupServiceImpl attrGroupService;
    @Autowired
    AttrAttrgroupRelationServiceImpl attrAttrgroupRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils baseList(Map<String, Object> params,String attr_type, Long catelogId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(qw->{
               qw.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        if(catelogId!=0){
            queryWrapper.eq("catelog_id", catelogId);
        }
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attr_type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> collect = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //查询 分类名称
            CategoryEntity byId = categoryService.getById(attrEntity.getCatelogId());
            if(byId!=null){
                attrRespVo.setCatelogName(byId.getName());
            }
            if("base".equalsIgnoreCase(attr_type)){
                //查询 属性分组名称
                //查询关系表
                AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrRespVo.getAttrId()));
                if(attr_id!=null){
                    AttrGroupEntity byId2 = attrGroupService.getById(attr_id.getAttrGroupId());
                    attrRespVo.setGroupName(byId2.getAttrGroupName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Transactional
    @Override
    public void saveAttrAndRelation(AttrVo attrVo) {
        //保存attr属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        //保存属性和属性组的关系
        if(attrVo.getAttrType().intValue()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }
    }

    @Transactional
    @Override
    public void updateAttrAndRelation(AttrVo attrVo) {
        //保存attr属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);
        //保存属性和属性组的关系
        if(attrVo.getAttrType().intValue()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            //正常操作流程是不需要重新查询的，排除属性和属性和组关系不全的情况
            int attr_id = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));
            if(attr_id>0){
                attrAttrgroupRelationService.updateById(attrAttrgroupRelationEntity);
            }else{
                attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public AttrRespVo getAttrDetailById(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        //查询分类名称和分类路径
        CategoryEntity categoryEntity = categoryService.getById(attrRespVo.getCatelogId());
        attrRespVo.setCatelogName(categoryEntity.getName());
        Long[] catelogPath = categoryService.getCatelogPath(attrRespVo.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);
        //查询分组id和分组名称
        //只有基本属性才会关联分组
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //查询关系表
            AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId));
            attrRespVo.setAttrGroupId(attr_id.getAttrGroupId());
            //查询属性分组表
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(attr_id.getAttrGroupId());
            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
        }
        return attrRespVo;
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //查询分组对应的所有属性id
        //查询关系表
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        if(attrAttrgroupRelationEntities!=null&&attrAttrgroupRelationEntities.size()>0){
            //批量查询属性
            List<Long> attrIds = attrAttrgroupRelationEntities.stream().map(attrAttrgroupRelationEntity -> {
                return attrAttrgroupRelationEntity.getAttrId();
            }).collect(Collectors.toList());
            List<AttrEntity> attrEntities = this.list(new QueryWrapper<AttrEntity>().in("attr_id", attrIds));
            return attrEntities;
        }else{
            return null;
        }

    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
        //查询分组catelog_id
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
        //获取当前分类的id
        Long catelogId = attrGroupEntity.getCatelogId();
        //查询分类下的所有分组
        List<AttrGroupEntity> attrGroupEntityList = attrGroupService.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<Long> gorupIds = attrGroupEntityList.stream()
                .map(attrGroupEntity1 -> attrGroupEntity.getAttrGroupId())
                .collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list
                (new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", gorupIds));
        List<Long> collect = attrAttrgroupRelationEntities.stream()
                .map(attrAttrgroupRelationEntity -> attrAttrgroupRelationEntity.getAttrId())
                .collect(Collectors.toList());
        //查询所有的catelog_id对应的所有属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());;
        if(collect!=null&&collect.size()>0){
            queryWrapper.notIn("attr_id", collect);
        }
        //判断是否有参数进行模糊查询
        String key = (String) params.get("key");
        if (!org.apache.commons.lang.StringUtils.isEmpty(key)) {
            queryWrapper.and((w) -> {
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public List<AttrEntity> getCanSearchAttrs(List<Long> pAttrIds) {

        return this.list(new QueryWrapper<AttrEntity>().in("attr_id",pAttrIds).eq("search_type", 1));
    }

}